import java.util.ArrayList;
import java.util.List;

public class Demo4 {





    //最后返回的集合
    int[] ret;
    //对应下标数组
    int[] index;
    //交换时的辅助数组
    int[] tmpIndex;
    int[] tmpNums;

    public List<Integer> countSmaller(int[] nums) {
        ret = new int[nums.length];
        index = new int[nums.length];
        tmpIndex = new int[nums.length];
        tmpNums = new int[nums.length];

        //初始化index数组
        for(int i = 0;i<nums.length;i++){
            index[i] = i;
        }


        mergeSort(nums,0,nums.length-1);

        List<Integer> list = new ArrayList<>();
        for(int x:ret){
            list.add(x);
        }
        return list;


    }

    private void mergeSort(int[] nums, int left, int right) {

        if (left>=right)
            return;

        //1.选择中间元素
        int mid = (left+right)/2;
        //[left,mid] [mid+1,right]
        //2.处理左右两个区间
        mergeSort(nums,left,mid);
        mergeSort(nums,mid+1,right);


        //3.处理一左一右的情况
        int cur1 = left,cur2 = mid+1,i=0;
        while (cur1<=mid&&cur2<=right){ // 降序排列的数组
            if (nums[cur1]<=nums[cur2]){
                tmpNums[i] = nums[cur2];
                tmpIndex[i] = index[cur2];
                i++;
                cur2++;
            }else {
                ret[index[cur1]] += right-cur2+1;//核心
                tmpNums[i] = nums[cur1];
                tmpIndex[i++] = nums[cur1++];
            }

        }

        //处理剩余的排序工作
        while (cur1<=mid){
            tmpNums[i] = nums[cur1];
            tmpIndex[i++] = index[cur1++];
        }
        while (cur2<=right){
            tmpNums[i] = nums[cur2];
            tmpIndex[i++] = nums[cur2++];
        }

        //覆盖
        for(int j = left;j<=right;j++){
            nums[j] = tmpNums[j-left];
            index[j] = tmpIndex[j-left];
        }

    }


}














